#include "../../include/myfunc.h"
#include "../../include/direntop.h"
#include "../../include/threadPool.h"
#include "../../include/mysqlop.h"

int generatesalt(char *salt)
{
    int i, flag;
    srand(time(NULL));
    for (i = 0; i < SALT_LEN; i++)
    {
        if (i == 3 || i == 6 || i == SALT_LEN - 1)
        {
            salt[i] = '$';
            continue;
        }
        flag = rand() % 3;
        switch (flag)
        {
        case 0:
            salt[i] = rand() % 26 + 'a';
            break;
        case 1:
            salt[i] = rand() % 26 + 'A';
            break;
        case 2:
            salt[i] = rand() % 26 + '0';
            break;
        }
    }
    salt[SALT_LEN] = '\0';
}

int sql_init(MYSQL **mysql, char *passwd)
{
    MYSQL *ptmp = mysql_init(NULL);
    *mysql = ptmp;
    if (*mysql == NULL)
    {
        printf("mysql init error\n");
        return -1;
    }
    if (mysql_real_connect(*mysql, "127.0.0.1", "root",
                           passwd, "net_disk", 0, NULL, 0) == NULL)
    {
        printf("connect mysql server failed:%s", mysql_error(*mysql));
        mysql_close(*mysql);
        return -1;
    }
    if (mysql_set_character_set(*mysql, "utf8") != 0)
    {
        printf("set charater failed:%s", mysql_error(*mysql));
        mysql_close(*mysql);
        return -1;
    }
    return 0;
}

int start(event_t * evt) {
    int netFd= evt->netFd;
    char buf[1024];
    
    strcpy(buf, "1.登录\t2.注册\n输入数字选择操作:");
    //puts(buf);
    sendn(evt->netFd, buf, strlen(buf));
    // send(netFd, &train, sizeof(train.length)+train.length, MSG_NOSIGNAL);
    int num;
    int ret = recvn(netFd, &num, sizeof(int));
    printf("%d\n", num);
    puts("signing up");
    switch(num) {
        case 1:
            ret = sign_in(evt);
            THREAD_ERROR_CHECK(ret, "sign_in");
            break;
        case 2:
            puts("sign up");
            ret = sign_up(evt);
            THREAD_ERROR_CHECK(ret, "sign_up");
            break;
    }
    return 0;
}

int sign_up(event_t *evt)
{
    char sql[1024];
    usrdata_t * pusr = evt->usrdata;
    int netFd = evt->netFd;
    train_t train;
    int flag = 1;

    while(1) {
        //接收用户发来的用户名
        bzero(&train, sizeof(train));
        int ret = msgprocess(netFd, &train);
        strcpy(pusr->usrname, train.buf);
        //判断数据库中是否存在同名用户
        printf("pusr->name = %s\n", train.buf);
        printf("%d\n", flag);
        if(!search_usr(evt, NULL, pusr->usrname))
        {
            flag = 0;
            send(netFd, &flag, sizeof(int), MSG_NOSIGNAL);
            break;
        }
        flag = 1;
        send(netFd, &flag, sizeof(int), MSG_NOSIGNAL);
    }

    char salt[SALT_LEN+1];
    generatesalt(salt);         //生成并保存盐值
    strcpy(pusr->salt, salt);    

    sendn(netFd, salt, strlen(salt));   //服务端发送盐值

    msgprocess(netFd, &train);           //接收客户端发来的密文
    strcpy(pusr->crptpasswd, train.buf);
    puts(pusr->crptpasswd);
    
    pusr->pwdid = 0;

    bzero(pusr->pwd, sizeof(pusr->pwd));
    strcpy(pusr->pwd, pusr->usrname);

    //将用户信息插入数据库
    sprintf(sql, "insert into usrdata(usrname,salt,cryptpasswd,pwd)values('%s','%s','%s','%s')",
                pusr->usrname, pusr->salt, pusr->crptpasswd,pusr->pwd);
    SQL_QUERY(evt->mysql, sql);
    
    sprintf(sql, "select id from usrdata where usrname='%s'", pusr->usrname);
    SQL_QUERY(evt->mysql, sql);

    MYSQL_RES *res = mysql_store_result(evt->mysql);
    if (res == NULL)
    {
        printf("store result failed:%s", mysql_error(evt->mysql));
        mysql_close(evt->mysql);
        return -1;
    }

    MYSQL_ROW row = mysql_fetch_row(res);
    pusr->id = atoi(row[0]);  
    mysql_free_result(res);

    printf("ready to mkdir\n");
    mymkdir(evt, pusr->usrname);             //在根目录创建用户文件夹夹
    printf("finish to mkdir\n");
    
    mycd(evt, pusr->pwd);


    return 0;
}

int sign_in(event_t * evt) {
    
}

int search_usr(event_t * evt, usrdata_t * usr, char *usrname)
{
    char select_sql[1024] = {0};
    sprintf(select_sql, "select * from usrdata where usrname='%s'", usrname);
    SQL_QUERY(evt->mysql, select_sql);
    // if (mysql_query(mysql, select_sql) != 0)
    // {
    //     printf("mysql query faild:%s", mysql_error(mysql));
    //     mysql_close(mysql);
    //     return -1;
    // }
    MYSQL_RES *res = mysql_store_result(evt->mysql);
    if (res == NULL)
    {
        printf("store result failed:%s", mysql_error(evt->mysql));
        mysql_close(evt->mysql);
        return -1;
    }
    int num_row = mysql_num_rows(res);
    if(num_row == 0) {
        mysql_free_result(res);
        return 0;
    }
    else {
        if(usr != NULL) {
            int num_col = mysql_num_fields(res);
            MYSQL_ROW row = mysql_fetch_row(res);
            usr->id = atoi(row[0]);
            strcpy(usr->usrname, row[1]);
            strcpy(usr->salt, row[2]);
            strcpy(usr->crptpasswd, row[3]);
            strcpy(usr->pwd,row[4]);
            file_t file;
            search_file(evt, &file, usr->pwd);
            usr->pwdid = file.id;
        }
        mysql_free_result(res);
        return 1;
    }
}

int insert_file(event_t * evt, file_t * file) {
    char insert_sql[1024] = {0};

    sprintf(insert_sql, "insert into virtual_file(parent_id,filename,owner_id,md5,filesize,type)values(%d,'%s',%d,'%s',%d,'%c')",
        file->parent_id, file->filename, file->owner_id, file->md5, file->fileSize, file->type);
    SQL_QUERY(evt->mysql, insert_sql);

    return 0;
}

int search_file(event_t * evt, file_t * file, char * filename) {
    char sql[1024];
    sprintf(sql, "select * from virtual_file where owner_id = %d && parent_id = %d && filename = '%s'",
    evt->usrdata->id, evt->usrdata->pwdid, filename);
    SQL_QUERY(evt->mysql, sql);
    MYSQL_RES *res = mysql_store_result(evt->mysql);
    if(res == NULL) {
        printf("store result failed: %s", mysql_error(evt->mysql));
        mysql_close(evt->mysql);
        return -1;
    }
    int num_row = mysql_num_rows(res);
    if(num_row == 0) {
        mysql_free_result(res);
        return 0;
    }
    else {
        if(file != NULL) {
            int num_col = mysql_num_fields(res);
            MYSQL_ROW row = mysql_fetch_row(res);
            file->id = atoi(row[0]);
            file->parent_id = atoi(row[1]);
            strcpy(file->filename, row[2]);
            file->owner_id = atoi(row[3]);
            if(row[4][0] != '\0')
                strcpy(file->md5, row[4]);
            file->fileSize = atoi(row[5]);
            file->type = row[6][0];
        }
        mysql_free_result(res);
        return 1;
    }
}
#if 0
int main()                          //测试插入函数
{
    event_t evt;
    usrdata_t pusr;
    evt.usrdata = &pusr;
    pusr.id = 1;
    strcpy(pusr.pwd, "owner");
    sql_init(&evt.mysql, "12345678");
    mymkdir(pusr.pwd);             //在根目录创建用户文件夹夹
    file_t file;
    bzero(&file, sizeof(file));
    file.parent_id = 0;
    strcpy(file.filename, pusr.pwd);
    file.owner_id = evt.usrdata->id;
    file.fileSize = 4096;
    file.type = 'd';
    insert_file(&evt, &file);        //将新文件插入数据库中
    mysql_close(evt.mysql);
    return 0;
}
#endif

#if 0
int main()
{                                   //测试signup功能
    event_t evt;
    usrdata_t usr;
    evt.usrdata = &usr;
    sql_init(&evt.mysql, "12345678");
    int ret = search_usr(evt.mysql, "kelloc");
    ERROR_CHECK(ret, -1, "search_usr");
    if (ret == 1)
    {
        printf("usr exist\n");
    }
    else if(ret == 0)
    {
        printf("usr didin't exist");
    }
    strcpy(usr.usrname, "root");
    char salt[50];
    generatesalt(salt);
    strcpy(usr.crptpasswd, salt);
    bzero(salt, sizeof(salt));
    generatesalt(salt);
    strcpy(usr.salt, salt);
    strcpy(usr.pwd, usr.usrname);
    printf("%s   %s   %s   %s\n", usr.usrname, usr.salt, usr.crptpasswd, usr.pwd);
    ret = sign_up(&evt);
    if(ret == 0)
        printf("succed!\n");
    printf("id = %d", usr.id);
    mysql_close(evt.mysql);
    return 0;
}

#endif

#if 0
int main()
{ //测试usrsearch功能
    event_t evt;
    usrdata_t usr;
    evt.usrdata = &usr;
    sql_init(&evt.mysql, "12345678");
    int ret = search_usr(evt.mysql, "root");
    if (ret == 1)
    {
        printf("usr exist\n");
    }
    else
    {
        printf("usr didin't exist");
    }
    return 0;
}
#endif